const router = require('../router');
const Result = require('../../config/result');
const Auth = require('../../token/auth');
const {databaseToken} = require('../../config/databaseapi')
const {upload, cosUpload, cosDelete} = require('../../cos/cos');
const {checkUserInfo} = require("../../config/checking");

// 上传文件
router.post('/upload', upload.single('file'), new Auth().m, async (ctx) => {
  try {
    const res = await cosUpload(ctx.file.filename, ctx.file.path)
    // const url = "https://" + res.Location
    new Result(ctx, '上传成功', 200, res).answer()
  } catch (e) {
    new Result(ctx, '上传失败，服务器错误', 500).answer()
  }
});

// 删除文件
router.post('/deleteimg', new Auth().m, async ctx => {
  const {fileName} = ctx.request.body
  try {
    const res = await cosDelete(fileName)
    new Result(ctx, '删除成功', 200, res).answer()
  } catch (e) {
    new Result(ctx, '删除失败', 500, e).answer()
  }
})

// 用户信息修改
router.post('/userinfo', new Auth().m, async ctx => {
  checkUserInfo(ctx)
  const {id, name, address, logo} = ctx.request.body
  if (!id) {
    const query = `db.collection('user-info').add({
            data:[{
            name:'${name}',
            address:'${address}',
            logo:${JSON.stringify(logo)}
            }]})`
    try {
      const res = await databaseToken.add(query)
      new Result(ctx, '添加成功', 200, res).answer()
    } catch (e) {
      new Result(ctx, '添加失败', 500, e).answer()
    }
  } else {
    const query = `db.collection('user-info').doc('${id}').update({
            data:{
            name:'${name}',
            address:'${address}',
            logo:${JSON.stringify(logo)}
            }})`
    try {
      const res = await databaseToken.update(query)
      new Result(ctx, '修改成功', 200, res).answer()
    } catch (e) {
      new Result(ctx, '修改失败', 500, e).answer()
    }
  }
})

// 获取用户信息
router.get('/userinfo', new Auth().m, async ctx => {
  const query = `db.collection('user-info').get()`
  try {
    const res = await databaseToken.query(query)
    new Result(ctx, '获取成功', 200, res).answer()
  } catch (e) {
    new Result(ctx, '获取失败', 500, e).answer()
  }
})

module.exports = router.routes()